import router from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import {asyncRoutes} from '@/router/index'

// 路由前置守卫
const whiteList = ['/login','/404']
router.beforeEach(async (to,from,next)=>{
  nProgress.start()
  if(store.getters.token){
    //存在token
    if(to.path === '/login'){
      //跳转到主页
      next('/')//中转到主页
      // next(地址)并没有执行后置守卫
      nProgress.done()
    }else{
      if(!store.getters.userId){
        const {roles} = await store.dispatch('user/getUserInfo')
        //  console.log(roles.menus) // 数组 不确定 可能是8个 1个 0个
        //  console.log(asyncRoutes) // 数组 8个

        //筛选后的路由
        const filterRoutes = asyncRoutes.filter(item=>{
          //return fslae/true
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        // console.log(filterRoutes);
        router.addRoutes([...filterRoutes,{path:'*',redirect:'/404',hidden:true}])//添加动态路由信息到路由表
        next(to.path)//动态添加路由后，再次访问之前的路由，不会再有路由守卫，所以需要重新访问一次 router的已知缺陷
      }
      next()
    }
  }else{
    //没有token
    if(whiteList.includes(to.path)){
      next()
    }else{
      next('/login')//中转到登录页
      nProgress.done()
    }
  }
  })

  // 后置守卫
  router.afterEach(()=>{
    nProgress.done()
  })